<template>
  <div class="container">
    <div class="progress-wrap">
      <mu-linear-progress :size="8" color="#F0FFF6" mode="determinate" :value="percentage" />
      <div class="progress-pencent">
        已完成
        <b class="f20">{{percentage}}</b>%
      </div>

      <!-- <div class="mt20">
      就诊科室：{{detail.departmentName}}
      就诊日期：{{detail.recordsTime | format}}
      </div>-->
    </div>

    <div class="infinite-container" style="top:112px;bottom:30px;">
      <template v-for="(d, i) in questionData">
        <div class="qa" :key="i" v-show="d.show">
          <qa-item :d="d" :index="i" :key="i" :isAnswered="isAnswered"></qa-item>
        </div>
      </template>
    </div>

    <mu-flexbox class="qa-login login bgwhite" :gutter="1">
      <mu-flexbox-item>
        <mu-raised-button
          label="下一题"
          primary
          fullWidth
          class="btn-login"
          @click="goPage(1)"
          v-if="currentPage < (totalPage -1)"
        ></mu-raised-button>

        <mu-raised-button label="提交" fullWidth primary class="btn-login" @click="submit" v-else></mu-raised-button>
      </mu-flexbox-item>
    </mu-flexbox>
  </div>
</template>

<script>
import { commonAjax, RESTFUL_API, commonAjaxJson } from "@/api/api";
import QaItem from "@/components/QaItem";
// 每页显示的记录数
const PER_PAGE = 2;

export default {
  components: { QaItem },
  data() {
    return {
      questionData: [],
      currentPage: 0,
      person: JSON.parse(sessionStorage.familyPerson || "{}"),
      currentQuestionnaire: JSON.parse(
        sessionStorage.currentQuestionnaire || "{}"
      ),
      detail: {},
      isAnswered: false,
      totalPage: 1
    };
  },
  computed: {
    percentage() {
      if (this.questionData.length === 0) {
        return 0;
      }
      return Math.ceil((this.currentPage / this.totalPage) * 100);
    }
  },
  mounted() {
    this.getById();
  },
  methods: {
    getById() {
      const { fusPlanExecutionListId } = this.$route.query;
      if (!fusPlanExecutionListId) {
        return;
      }
      
      commonAjaxJson(
        RESTFUL_API.getDetailForPatient,
        { fusPlanExecutionListId },
        true
      ).then(res => {
        
        if (res.data.code == 200 && res.data.data) {
          const da = res.data.data;
          // 已回答的不能修改
          if (da.satisfactionStatus == 2) {
            this.isAnswered = true;
          }
          this.detail = da;
          this.getQuestionnaireDetail(res.data.data);
        }
      });
    },
    // 获取文件平台文件
    getQuestionnaireDetail(item) {
      
      let params = {
        deviceType: 2,
        questionnaireId: item.questionnaireInfoId,
        showType: 1,
        uid: item.patientCode || item.patientId
      };
      commonAjaxJson(RESTFUL_API.getQuestionnaireDetail, params, true).then(
        res => {
          
          if (res.data.code == 200 && res.data.data) {
            const d = res.data.data;
            // 更新页面标题
            document.title = d.questionnaireName;
            this.questionData = this.getList(d.titles);
            this.totalPage = Math.ceil(this.questionData.length / PER_PAGE);
          }
        }
      );
    },

    // 过滤原始数据
    getList(arr) {
      let temp = [];
      arr.forEach((v, i) => {
        // v.show = Math.floor(i / PER_PAGE) === this.currentPage;
        v.show = i < 3;
        // 单选\下拉
        if (v.widgetType == 1 || v.widgetType == 3) {
          v.model = "";
          if (v.options && v.options.length > 0) {
            temp.push(v);
          }
        }

        // 多选
        if (v.widgetType == 2) {
          v.model = [];
          if (v.options && v.options.length > 0) {
            temp.push(v);
          }
        }

        // 单项填空
        if (v.widgetType == 6) {
          v.model = "";
          temp.push(v);
        }
      });
      return temp;
    },

    goPage(page) {
      if (!this.checkRule()) {
        this.$store.commit("UPDATE_TOAST", { message: "请填写完整！" });
        return;
      }
      this.currentPage += page;
      if (this.currentPage >= this.totalPage) {
        return;
      }
      this.questionData.forEach((v, i) => {
        v.show = Math.floor(i / PER_PAGE) === this.currentPage;
      });
    },
    checkRule() {
      let result = true;
      this.questionData.forEach((v, i) => {
        if (Math.floor(i / PER_PAGE) === this.currentPage) {
          if (v.model.length === 0) {
            result = false;
          }
        }
      });
      return result;
    },
    getAnseredList() {
      let titles = this.questionData;
      let temp = [];

      titles.forEach(v => {
        let answerContent = "";
        let optionId = "";
        let answerDesc = "";

        // 单选答案 下拉
        if (v.widgetType == 1 || v.widgetType == 3) {
          answerContent = this.getContentFromOptionId(v.options, v.model);
          optionId = v.model;
          answerDesc = v.optionExplain;
        }

        // 多选答案
        if (v.widgetType == 2) {
          answerContent = [];
          v.model.forEach(a => {
            answerContent.push(this.getContentFromOptionId(v.options, a));
          });
          answerContent = answerContent.join("|");
          optionId = v.model.join(",");
          answerDesc = v.optionExplain;
        }

        // 字典选择
        if (v.widgetType == 4) {
          answerContent = v.model;
        }
        // 级联选择
        if (v.widgetType == 5) {
          answerContent = [];
          v.model.forEach(a => {
            answerContent.push(this.getContentFromOptionId(v.options, a));
          });
          answerContent = answerContent.join("|");
          optionId = v.model.join(",");
        }

        // 单项填空
        if (v.widgetType == 6) {
          answerContent = v.model;
        }

        // 多项填空
        if (v.widgetType == 7) {
          answerContent = [];
          optionId = [];
          v.options.forEach(a => {
            if (a.optionExplain) {
              answerContent.push(a.optionExplain);
              optionId.push(a.optionId);
            }
          });
          answerContent = answerContent.join("|");
          optionId = optionId.join(",");
        }

        // 文件上传
        if (v.widgetType == 8) {
          answerContent = v.model;
        }

        // 矩阵
        if (v.widgetType == 9) {
          answerContent = JSON.stringify(v.model);
        }

        let p = {
          titleId: v.titleId,
          optionType: v.widgetType,
          answerDesc,
          optionId,
          answerContent
        };

        // 只保存前9个组件的答案
        if (v.widgetType < 10) {
          temp.push(p);
        }
      });
      return temp;
    },
    getContentFromOptionId(arr, optionId) {
      if (!optionId) {
        return "";
      }
      return arr.filter(v => v.optionId == optionId)[0].optionContent;
    },
    addInputAnswer(v) {
      let temp = [];
      if (v.options[0].model.length > 0) {
        let input = v.options[0];
        temp.push({
          // qId: input.value,
          inquirer: input.inquirer,
          infoqid: input.infoqid,
          subjectqid: input.subjectqid,
          content: input.model
        });
      }
      return temp;
    },
    addRadioAnswer(v) {
      let temp = [];
      if (v.model.length > 0) {
        let v2 = v.options[0];
        temp.push({
          // qId: v2.value,
          inquirer: v2.inquirer,
          infoqid: v2.infoqid,
          subjectqid: v2.subjectqid,
          answerqid: +v.model
        });
      }
      return temp;
    },
    addCheckboxAnswer(v) {
      let temp = [];
      if (v.model.length > 0) {
        v.model.forEach(v1 => {
          v.options.forEach(v2 => {
            if (v1 === v2.value) {
              temp.push({
                // qId: v.value,
                inquirer: v2.inquirer,
                infoqid: v2.infoqid,
                subjectqid: v2.subjectqid,
                answerqid: +v2.value
              });
            }
          });
        });
      }
      return temp;
    },
    submit() {
      this.saveQuestionnaireResult();
    },
    // 保存随访记录
    saveQuestionnaireResult() {
      const d = this.detail;
      let params = {
        fusMedicalRecordsId: d.fusMedicalRecordsId,
        doctorCode: d.doctorCode,
        doctorName: d.doctorName,
        doctorUserId: "",
        questionnaireInfoId: d.questionnaireInfoId,
        resultCode: 1,
        resultText: "成功",
        fusPlanExecutionListId: d.fusPlanExecutionListId
      };
      
      commonAjaxJson(RESTFUL_API.saveQuestionnaireResult, params, true).then(
        res => {
          
          if (res.data.code == 200) {
            this.editorAnswerSave();
          }
        }
      );
    },

    // 保存问卷
    editorAnswerSave() {
      const d = this.detail;

      let params = {
        questionnaireId: d.questionnaireInfoId,
        userId: d.patientCode || d.patientId,
        userName: d.patientName || "",
        phoneNum: d.patientMobile || "",
        investigatorId: d.doctorCode,
        investigatorName: d.doctorName,
        questionnaireWay: 1, // 电话问诊|视频问诊
        answerState: 1,
        answers: this.getAnseredList()
      };
      
      commonAjaxJson(RESTFUL_API.editorAnswerSave + "?t=1", params, true).then(
        res => {
          
          if (res.data.code == 200) {
            this.$store.commit("UPDATE_TOAST", {
              message: res.data.msg || "提交成功",
              fn: () => this.$router.replace("/questionnaire/thankyou")
            });
          } else {
            this.$store.commit("UPDATE_TOAST", {
              message: res.data.msg || "提交失败"
            });
          }
        }
      );
    }
  }
};
</script>

<style lang='less' scoped>
@import "../../common/css/vars.less";
.qa-login {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
}
.progress-wrap {
  background: url(../../assets/myd_bg_tm.png) no-repeat;
  background-size: 100%;
  height: 112px;
  padding: 40px 20px;
  position: absolute;
  z-index: 10;
  right: 0;
  top: 0;
  left: 0;
  color: #fff;
  .mu-linear-progress {
    background-color: #00b766;
  }
}
.qa {
  border-bottom: 1px solid @color-border;
  background: #fff;
  margin-bottom: 1em;
  padding: 10px 10px 10px 10px;
  .title {
    color: #999;
    padding-bottom: 1em;
  }

  .progress {
    // background: #fff;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #999;
  }
  .mu-text-field-input {
    border: 1px solid #eee;
    padding: 0 10px;
  }
}
.progress-pencent {
  position: absolute;
  top: 10px;
}
</style>
